package org.langqiao.thread;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class BallsCanvas extends Canvas implements ActionListener,FocusListener {//画布响应定时、焦点事件
	private Ball balls[];//画多个球
	private Timer timer;//定时器
	public BallsCanvas(Color colors[],int delay)//构造函数，指定颜色，延时
	{
		this.balls=new Ball[colors.length];
		for(int i=0,x=40;i<colors.length;i++,x+=40)
		{
			balls[i]=new Ball(x,x,colors[i]);//每个小球对应的坐标位置和颜色
		}
		this.addFocusListener(this);//注册焦点监听器
		timer=new Timer(delay,this);//定时器
		timer.start();//定时器启动		
	}
	private static class Ball//内部类
	{
		int x,y;//坐标
		Color color;//颜色
		boolean up,left;//运到方向
		Ball(int x,int y,Color color)//内部类Ball的构造函数
		{
			this.x=x;
			this.y=x;
			this.color=color;
			up=left=false;
		}
	}
	public void setDelay(int delay)//设置延时
	{
		timer.setDelay(delay);
	}
	public void paint(Graphics g)//在Canvas画图
	{
		for(int i=0;i<balls.length;i++)
		{
		    g.setColor(balls[i].color);//设置颜色
		    balls[i].x=balls[i].left?balls[i].x-10:balls[i].x+10;
		    if(balls[i].x<=0||balls[i].x>=this.getWidth())
		    	balls[i].left=!balls[i].left;//到框架窗口边缘水平边时，更改方向
		    balls[i].y=balls[i].up?balls[i].y-10:balls[i].y+10;
		    if(balls[i].y<=0||balls[i].y>=this.getHeight())
		    	balls[i].up=!balls[i].up;
		    	g.fillOval(balls[i].x,balls[i].y,20,20);//画圆
		    
		}
	}
	public void actionPerformed(ActionEvent e)
	{
		repaint();
	}
	public void focusGained(FocusEvent e)
	{
		timer.stop();
	}
	public void focusLost(FocusEvent e)
	{
		timer.restart();
	}
}
public class BallsJFrame extends JFrame implements ChangeListener
{
	private BallsCanvas ball;
	private JSpinner spinner;
	public BallsJFrame()
	{
		super("弹弹球");
		this.setBounds(300,400,300,400);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		Color colors[]={Color.red,Color.green,Color.yellow,Color.blue,Color.black};
		ball=new BallsCanvas(colors,100);
		this.getContentPane().add(ball);
		
		JPanel panel=new JPanel();
		this.getContentPane().add(panel,"South");
		panel.add(new JLabel("Delay"));
		spinner=new JSpinner();
		spinner.setValue(100);
		panel.add(spinner);
		spinner.addChangeListener(this);
		this.setVisible(true);
	}
	public void stateChanged(ChangeEvent e)
	{
		ball.setDelay(Integer.parseInt(""+spinner.getValue()));
	}
	public static void main(String[] args)
	{
		new BallsJFrame();
    }
}
